package com.jsmile.cloud.tradecenter.order.factory;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.stereotype.Component;

import com.jsmile.cloud.goodscenter.api.res.ResSku;
import com.jsmile.cloud.tradecenter.api.req.ReqOrderCreate;
import com.jsmile.cloud.tradecenter.api.req.SplitOrder;
import com.jsmile.cloud.tradecenter.api.res.ResOrder;
import com.jsmile.cloud.tradecenter.api.res.ResOrderList;
import com.jsmile.cloud.tradecenter.order.model.Order;

import cn.hutool.core.bean.BeanUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
@AllArgsConstructor
public class OrderCreateFactory {

    /**
     * 订单检查
     */
    public void toPay(List<Order> orders) {
        OrderCheckFactory.build(orders);
    }

    /**
     * 订单创建
     */
    public List<Order> create(ReqOrderCreate reqOrderCreate) {
        OrderCheckKit orderCheckKit = OrderCheckFactory.build(reqOrderCreate);
        orderCheckKit.setHasEvent(true);
        List<Order> orders = createOrder(orderCheckKit);
        return orders;
    }

    /**
     * 订单预览
     */
    public ResOrderList preview(ReqOrderCreate reqOrderCreate) {
        ResOrderList resOrderList = BeanUtil.toBean(reqOrderCreate, ResOrderList.class);
        OrderCheckKit orderCheckKit = OrderCheckFactory.build(reqOrderCreate);
        resOrderList.setOrders(createOrder(orderCheckKit).stream().map(x -> {
            ResOrder resOrder = BeanUtil.toBean(x, ResOrder.class);
            resOrder.setOrderNo(x.getId());
            return resOrder;
        }).collect(Collectors.toList()));
        return resOrderList;
    }

    /**
     * 构造订单预览和创建的参数
     */
    private List<Order> createOrder(OrderCheckKit orderCheckKit) {
        Map<Long, ResSku> skuMap = orderCheckKit.getSkuList().stream().collect(Collectors.toMap(ResSku::getSkuId, a -> a, (k1, k2) -> k1));
        Map<SplitOrder, List<ReqOrderCreate.OrderSku>> orderMap =
            orderCheckKit.getReqOrderCreate().getSkuList().stream().collect(Collectors.groupingBy(ReqOrderCreate.OrderSku::getSplitOrder));
        return orderMap.keySet().stream().map(key -> {
            Order order = Order.create(orderCheckKit, key, skuMap, orderMap.get(key));
            return order;
        }).collect(Collectors.toList());
    }

}
